import NetInfo from "@react-native-community/netinfo";
import Config from "react-native-config";
import Utils from "../libs/Utils";
import XLog from "../libs/XLog";
import DataCenter from "./DataCenter";
import { RegisterType, SerialConfig, MeterConfig, AUTOINIT_INTERVAL, LOOP_CONTROLLER_QUERY_INTERVAL, METER_QUERY_INTERVAL, ProductID } from "./LogicConstant";
import { register } from "../Http/HttpService";
import CommunicationManager from "./CommunicationManager";
import CommandManager from "./CommandManager";
import StrategyManager from "./StrategyManager";
import SerialPortManager from "./SerialPortManager"
import AsyncDataManager from "./AsyncDataManager";
import ErrorRecoveryManager from "./ErrorRecoveryManager";
import DebugManager from "./DebugManager";
import { checkIpValid } from "./Utils";
import HardwareConfigManager from "./HardwareConfigManager";

export default class MainLogicLoop {
    static async doRegisterLogic(serverIp, code) {
        let netInfoState = await NetInfo.fetch();
        if(netInfoState.isConnected && checkIpValid(DataCenter.machineIp)) {
            const{success, data, message} = await register(DataCenter.machineIp, serverIp, code, await AsyncDataManager.getDeviceConstInfo());
            if(success) {
                DataCenter.doRegisterSuccess(data);
                return RegisterType.REGISTER_SUCCESS;
            } else {
                DataCenter.doRegisterFail(RegisterType.REGISTER_ERROR, message);
                return RegisterType.REGISTER_ERROR;
            }
        } else {
            DataCenter.doRegisterFail(RegisterType.REGISTER_NO_NET, "当前无网络");
            return RegisterType.REGISTER_NO_NET;
        }
    }

    static async uninstallMainLoop() {
        StrategyManager.uninstallStrategyLogic();
        await CommunicationManager.uninstallMqttLogic();
        AsyncDataManager.uninstallAsyncManagerLogic();
    }

    static async installMainLoopLogic() {
        try{
            await this.startSerialPortLogic();
            await CommunicationManager.installMqttLogic();
            CommandManager.installCommandLogic();
            StrategyManager.installStrategyLogic();
            AsyncDataManager.installAsyncManagerLogic();
        }catch(error) {
            XLog.e("installMainLoopLogic exception:", error?.message);
        }
    }

    static async startSerialPortLogic(){
        // 创建回路控制器串口设备，并发送查询地址消息，并按时间间隔查询设备状态
        await SerialPortManager.removeAllDevice();
        await SerialPortManager.createDevice(ProductID.LOOP, DataCenter.loopControllerList);
        await SerialPortManager.createDevice(ProductID.SMART, DataCenter.smartMeterList);
        CommandManager.installSerialEvent();
        // SerialPortManager.sendLoopControllerRequest({"event": "readAddress"});
        // SerialPortManager.sendLoopControllerRequest({"event": "readVersion"});
        // for(var device of (DataCenter.loopControllerList||[])){
        //     //SerialPortManager.sendLoopControllerRequest({"event": "readAddress"}, device.index);
        //     //SerialPortManager.sendLoopControllerRequest({"event": "readVersion"}, device.index);
        // }  
        this.serialLoopInfoTimer = setInterval(()=>{
            for(var device of (DataCenter.loopControllerList||[])){
                SerialPortManager.sendLoopControllerRequest({"event": "readLight"}, device.index);
            }            
        }, LOOP_CONTROLLER_QUERY_INTERVAL/1);
        
        this.serialMeterInfoTimer = setInterval(()=>{
            for(var device of (DataCenter.smartMeterList||[])){
                SerialPortManager.sendMeterRequest(device.index);
            }            
        }, METER_QUERY_INTERVAL/1);
        //}, 60000);
    }

    static stopSerialPortLogic(){
        if(this.serialLoopInfoTimer){
            clearInterval(this.serialLoopInfoTimer);
        }
        if(this.serialMeterInfoTimer){
            clearInterval(this.serialMeterInfoTimer);
        }
    }

    static async startLogic() {
        try{
            // Utils.installNetMonitor(async(data)=>{
            //     if(data.event == "disconnect") {
            //         XLog.e("net disconnect");
            //     } else if(data.event = "connect") {
            //         XLog.e("net connect");
            //         let ip = await Utils.getMachineIp();
            //         if(ip != DataCenter.machineIp) {
            //             XLog.e("net connect ip change:", DataCenter.machineIp, ip);
            //             DataCenter.machineIp = ip;
            //             if(DataCenter.isMaster) {//如果我是master
            //                 DataCenter.masterIp = ip;
            //                 await CommunicationManager.destroyLocalMqttClient();
            //                 await CommunicationManager.createLocalMqttClient();
            //             }
            //         }
                    
            //     }
            // });

            NetInfo.addEventListener(async(state)=>{
                const{isConnected} = state;
                if(isConnected) {
                    XLog.e("net connect");
                    let ip = await Utils.getMachineIp();
                    if(ip != DataCenter.machineIp) {
                        XLog.e("net connect ip change:", DataCenter.machineIp, ip);
                        DataCenter.machineIp = ip;
                        if(DataCenter.isMaster) {//如果我是master
                            DataCenter.masterIp = ip;
                            await CommunicationManager.destroyLocalMqttClient();
                            await CommunicationManager.createLocalMqttClient();
                        }
                    }
                } else {
                    XLog.e("net disconnect");
                }
            });
            await HardwareConfigManager.reloadConfig();
            DataCenter.machineIp = await Utils.getMachineIp();
            DataCenter.reloadAllFromCache();
            ErrorRecoveryManager.installErrorRecoveryManager();
            DebugManager.installDebugManager();
            if(DataCenter.registerStatus == RegisterType.REGISTER_SUCCESS) {
                await this.installMainLoopLogic();
            } else {
                //await this.startSerialPortLogic();
            }
        }catch(error) {
            XLog.e("main logic exception:",error?.message);
        }
    }
}